package seedmarket

import org.springframework.dao.DataIntegrityViolationException


/**
 * Acts as the controller for the Admin. It provides logic for what an Admin can do.
 * @author Gregory Koutrelakos
 * @version 7.11.12
 *
 */
class AdminController {

	/**
	 * Tells the Admin what methods to allow. Default is "POST" meaning all
	 */
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	/**
	 * The default method for the index of the Admin
	 * @return redirects to the list of the Admin
	 */
    def index() {
        redirect(action: "list", params: params)
    }
	
	/**
	 * Represents the login page. No logic required. See authenticate
	 */
	def login = {}
	
	/**
	 * Holds the logic for logging in/authenticating an Admin
	 */
	def authenticate = {
		//first finds the admin in the system by username and password
		def admin = Admin.findByUserNameAndPassword(params.userName, params.password)
		//checks to see if the admin is there
		if(admin){
			session.admin = admin //the current session is equal to the admin
			flash.message = "Hello Admin ${admin.fullName}!" //displays a flash message, welcoming the admin
			redirect(action:"list") //redirects the admin to the list of admins
			
		}
		//if the admin isn't found
		else{
		//displays flash message notifying the user that the login was incorrect
		flash.message = "Sorry, ${params.userName}. Please try again." 
		redirect(action:"login") //redirects back to the login
		}
	}
	
	/**
	 * Logs the Admin out of the system
	 */
	def logout = {	
		//first finds the admin in the system
		def admin = Admin.findByUserNameAndPassword(params.userName, params.password)
		//if the admin is found
		if(admin) {
			//displays a flash message letting the admin know that they logged out
			flash.message = "Goodbye Admin ${session.admin.fullName}"
			//sets the admin's current session to null 
			session.admin = null
			//redirects back to the login page
			redirect(action:"login")
		}
		//if admin is not found in the system
		else {
			//displays a message asking the admin to log in first
			flash.message = "Sorry, you need to log in first."
			redirect(action:"login") //redirects back to login
		}
	}

	/**
	 * The list of admins page
	 * @return the complete list of admins in the grails format
	 */
    def list() {
		//sets up the number of entries maximum
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		//lists the admins
        [adminInstanceList: Admin.list(params), adminInstanceTotal: Admin.count()]
    }

	/**
	 * The page for creating a new Admin
	 * @return newly created admin
	 */
    def create() {
		//the instance of the new admin created
        [adminInstance: new Admin(params)]
    }

	/**
	 * The page for when the admin has been saved to the system.
	 * @return the saved admin
	 */
    def save() {
		//gets the instance of the admin to be saved
        def adminInstance = new Admin(params)
		//checks if the admin instance can be saved (all validations true)
        if (!adminInstance.save(flush: true)) {
			//creates the view from the create method
            render(view: "create", model: [adminInstance: adminInstance])
            return
        }
		//displays a message saying the admin has been saved and redirects to the show page
		flash.message = message(code: 'default.created.message', args: [message(code: 'admin.label', default: 'Admin'), adminInstance.id])
        redirect(action: "show", id: adminInstance.id)
    }

	/**
	 * The show page of the Admin class
	 * @return the information of the admin
	 */
    def show() {
		//gets the current admin instance
        def adminInstance = Admin.get(params.id)
		//checks to see if the admin instance isn't valid
        if (!adminInstance) {
			//informs the user that the instance is false and redirects to the list
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'admin.label', default: 'Admin'), params.id])
            redirect(action: "list")
            return
        }

        [adminInstance: adminInstance]
    }

	/**
	 * The edit page of the admin class. Is used in update so return null
	 * @return null
	 */
    def edit() {
		//gets the instance of the admin
        def adminInstance = Admin.get(params.id)
		//checks to see if it's valid then performs accordingly
        if (!adminInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'admin.label', default: 'Admin'), params.id])
            redirect(action: "list")
            return
        }

        [adminInstance: adminInstance]
    }

	/**
	 * Will display the page that updates the Admin
	 * @return the updated admin
	 */
    def update() {
		//first it will get the instance and check if it's valid
        def adminInstance = Admin.get(params.id)
        if (!adminInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'admin.label', default: 'Admin'), params.id])
            redirect(action: "list")
            return
        }
		//if the admin checks out, it will look at the current instance and make the necessary changes to the page
        if (params.version) {
            def version = params.version.toLong()
            if (adminInstance.version > version) {
                adminInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'admin.label', default: 'Admin')] as Object[],
                          "Another user has updated this Admin while you were editing")
                render(view: "edit", model: [adminInstance: adminInstance])
                return
            }
        }
		//properties are equal to the new parameters entered
        adminInstance.properties = params

		//checks if new instance can be saved
        if (!adminInstance.save(flush: true)) {
            render(view: "edit", model: [adminInstance: adminInstance])
            return
        }
		//displays message and shows the updated page
		flash.message = message(code: 'default.updated.message', args: [message(code: 'admin.label', default: 'Admin'), adminInstance.id])
        redirect(action: "show", id: adminInstance.id)
    }

	/**
	 * Will delete an existing admin
	 * @return message informing the user that the admin has been deleted
	 */
    def delete() {
		//gets the instance and checks if it is valid
        def adminInstance = Admin.get(params.id)
        if (!adminInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'admin.label', default: 'Admin'), params.id])
            redirect(action: "list")
            return
        }

		//tries to delete the admin desired
        try {
            adminInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'admin.label', default: 'Admin'), params.id])
            redirect(action: "list")
        }
		//catches the exception that the data integrity isn't true
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'admin.label', default: 'Admin'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
